package com.skyworth.web.wechat.crons;

import com.skyworth.utils.StrUtil;
import com.skyworth.web.wechat.common.AppSecretInfo;
import com.skyworth.web.wechat.engin.ServerEngin;
import com.skyworth.web.wechat.entity.AccessTokenModel;
import com.skyworth.web.wechat.entity.TicketModel;
import com.skyworth.web.wechat.service.AccessTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.Map;

/**
 * Created by yuhaichao on 2016/8/24.
 */

@Component
public class ScheduledServices {

    @Autowired
    private AccessTokenService accessTokenService;

    @Scheduled(fixedRate = 1000 * 60 * 110)
    public void tokenFixedrate(){
        String localStr="";
        try{
            InetAddress localAddr =InetAddress.getLocalHost();
            localStr=localAddr.getHostAddress();
        }catch(Exception e){
            e.printStackTrace();
        }
        if("10.135.30.37".equals(localStr)){
            Map<Object,Object> accessTokenMap = ServerEngin.getInstance().getAccessToken(AppSecretInfo.appId,AppSecretInfo.appSecret);
            if(accessTokenMap!=null) {
                AccessTokenModel at = new AccessTokenModel();
                at.setAppId(AppSecretInfo.appId);
                at.setAccessToken(StrUtil.objectToString(accessTokenMap.get("access_token")));
                accessTokenService.saveToken(at);

                Map<Object,Object> ticketMap = ServerEngin.getInstance().getTicket(at.getAccessToken());
                if(ticketMap!=null){
                    TicketModel tm = new TicketModel();
                    tm.setAppId(AppSecretInfo.appId);
                    tm.setTicket(StrUtil.objectToString(ticketMap.get("ticket")));
                    accessTokenService.saveTicket(tm);
                }

            }
        }
    }
}
